package com.hailiao.beidou.message.ui.page.status

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.d10ng.app.managers.PermissionManager
import com.d10ng.common.base.toStringWithMaxDecimal
import com.d10ng.compose.model.UiViewModelManager
import com.d10ng.compose.ui.dialog.builder.ConfirmDialogBuilder
import com.d10ng.datelib.toDateStr
import com.hailiao.beidou.message.R
import com.hailiao.beidou.message.bd.Beidou
import com.hailiao.beidou.message.data.location.LocationRepository
import com.hailiao.beidou.message.utils.locationPermissionArray
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

/**
 * 设备状态
 * @Author d10ng
 * @Date 2023/11/17 16:55
 */
class StatusScreenViewModel: ViewModel() {

    // 本机设备状态
    val deviceStatusListFlow = LocationRepository.locationFlow.map {
        listOf(
            DeviceStatusData(R.drawable.status_satellite_count, "定位卫星", it?.satelliteCount?.toString()?.let { i -> i + "个" }?: "--"),
            DeviceStatusData(R.drawable.status_time, "卫星授时", it?.timestamp?.toDateStr("yyyy.MM.dd HH:mm")?: "--"),
            DeviceStatusData(R.drawable.status_location, "经纬度", it?.getPointShowString()?: "--"),
            DeviceStatusData(R.drawable.status_altitude, "高程", it?.altitude?.toStringWithMaxDecimal(2)?.let { i -> i + "米" }?: "--"),
        )
    }
    // 北斗设备连接状态
    val isBDConnectedFlow = Beidou.statusFlow.map { it.isConnected }
    // 北斗设备状态
    val bdDeviceStatusListFlow = (Beidou.getDeviceStatusFlow()?: flow { emit(listOf()) }).map {
        it.toDeviceStatusDataList()
    }
    // 北斗信号值
    val bdSignalValueFlow = Beidou.signalValueFlow

    init {
        viewModelScope.launch {
            // 请求定位权限
            if (PermissionManager.request(locationPermissionArray)) {
                LocationRepository.start()
            }
        }
    }

    override fun onCleared() {
        LocationRepository.stop()
        super.onCleared()
    }

    /**
     * 点击断开蓝牙连接
     */
    fun onClickDisconnect() {
        UiViewModelManager.showDialog(ConfirmDialogBuilder(
            content = "是否断开北斗终端连接？",
            onConfirmClick = {
                CoroutineScope(Dispatchers.IO).launch {
                    Beidou.disconnect()
                }
                true
            }
        ))
    }
}